
define([
], function () {
  'use strict'
  /**
 * 根据后端数据流下载文件
 * @param {BlobPart} res 数据流
 * @param {string} filename 文件名
 * @param {BlobPropertyBag} BlobProperty
 */
  function downloadResopnse(res, filename, BlobProperty = { type: 'application/vnd.ms-excel;charset=utf-8' }) {
    const blob = new Blob([res.data], BlobProperty) // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
    let download = ''
    if (!filename) {
      function parseContent(content) {
        const list = content.split(';')
        const obj = {}
        list.forEach(item => {
          const [key, val] = item.split('=')
          obj[key.replace(/\s/g, '')] = val?.replace(/\"/g, '')
        })
        return obj
      }
      let content = res.headers['content-disposition']
      const result = parseContent(content)
      download = decodeURIComponent(result.filename)
    } else {
      download = filename
    }
    downLoadURL(blob, download)
  }

  /**
 * 根据地址下载文件
 * @param {string} href
 * @param {string} fileName
 */
  function downLoadURL(href, fileName) {
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    if (href instanceof Blob) {
      elink.href = URL.createObjectURL(href)
    } else {
      elink.href = href
    }
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  }
  return {
    downLoadURL,
    downloadResopnse
  }
})
